package com.tran.app.viewmodel

import android.text.TextUtils
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tran.app.MyApp
import com.tran.app.dao.AppDatabase
import com.tran.app.data.RegisterUi
import com.tran.app.utils.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class UpdateUserInfoVM:ViewModel() {

    private val _uidata = MutableStateFlow<RegisterUi>(RegisterUi())
    val uidata: StateFlow<RegisterUi> = _uidata.asStateFlow()

    fun registerUser(){
        if(TextUtils.isEmpty(uidata.value.userInfo.name)){
            show("用户名不能为空")
            return
        }
        if(TextUtils.isEmpty(uidata.value.pw2)|| TextUtils.isEmpty(
                uidata.value.pw
            )){
            show("密码不能为空")
            return
        }
        if(TextUtils.isEmpty(uidata.value.userInfo.email)){
            show("邮箱不能为空")
            return
        }
        if(TextUtils.isEmpty(uidata.value.userInfo.sex)){
            show("性别不能为空")
            return
        }
        if(TextUtils.isEmpty(uidata.value.userInfo.realName)){
            show("真实姓名不能为空")
            return
        }
        if(TextUtils.isEmpty(uidata.value.userInfo.kind)){
            show("系不能为空")
            return
        }
        if(TextUtils.isEmpty(uidata.value.userInfo.grade)){
            show("班级不能为空")
            return
        }
        if(uidata.value.pw!=uidata.value.pw2){
            show("两次密码输入不相等")
            return
        }
        _uidata.value = uidata.value.copy(userInfo = uidata.value.userInfo.copy(pw = uidata.value.pw2))
        val user = uidata.value.userInfo
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                try {
                    _uidata.value = _uidata.value.copy(isloading = true)
                    AppDatabase.getInstance(MyApp.instance).userInfoDao().update(user)
                    delay(1500)
                    _uidata.value = _uidata.value.copy(isloading = false)
                    withContext(Dispatchers.Main){
                        show("修改成功")
                    }
                }catch (e:Exception){
                    withContext(Dispatchers.Main){
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    fun setuidata(ui:RegisterUi){
        _uidata.update {
            ui
        }
    }

    init {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                val user = AppDatabase.getInstance(MyApp.instance).userInfoDao().getUserByName(MyApp.user)
                _uidata.update {
                    it.copy(userInfo = user!!)
                }
            }
        }
    }
}